package cn.fetosoft.woodpecker.controller;

import cn.fetosoft.commons.secret.HmacSHA1Signer;
import cn.fetosoft.woodpecker.config.Constant;
import cn.fetosoft.woodpecker.core.data.entity.User;
import cn.fetosoft.woodpecker.core.data.form.UserForm;
import cn.fetosoft.woodpecker.core.data.service.UserService;
import cn.fetosoft.woodpecker.core.exceptions.ValidatorException;
import cn.fetosoft.woodpecker.core.util.RandomUtil;
import cn.fetosoft.woodpecker.struct.DataGrid;
import cn.fetosoft.woodpecker.struct.UserIdentity;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户控制器
 * @author guobingbing
 * @wechat t_gbinb
 * @since 2021/7/14 21:48
 */
@Slf4j
@Controller
@RequestMapping("/auth/user")
public class UserController extends BaseController {

	private static final String NAME_ADMIN = "admin";
    @Autowired
    private UserService userService;

    @RequestMapping("/main")
    public String main(){
        return "/user/main";
    }

    /**
     * 查询用户信息
     * @param form
     * @return
     */
    @RequestMapping("/getUsers")
    @ResponseBody
    public String getUsers(@ModelAttribute UserForm form){
        DataGrid<User> dataGrid = new DataGrid<>();
        form.setAscField("createTime");
        try {
            long total = userService.selectCountByForm(form, User.class);
            dataGrid.setTotal(total);
            if(total>0){
                List<User> list = userService.selectListByForm(form, User.class);
                dataGrid.setRows(list);
            }
        }catch (Exception e){
            log.error("getUsers", e);
        }
        return dataGrid.toJsonString();
    }

    /**
     * 创建
     * @return
     */
    @RequestMapping("/create")
    @ResponseBody
    public String create(@ModelAttribute User user){
        Result<String> result = Result.errorResult();
        try{
        	user.setId(new ObjectId().toString());
            user.setUserId("U" + RandomUtil.getLenRandom(8));
            user.setCreateTime(System.currentTimeMillis());
            user.setPassword(HmacSHA1Signer.signString(user.getPassword(), Constant.HMAC_SHA1_KEY));
            userService.insert(user);
			result.setStatus(Result.SUCCESS);
        }catch (ValidatorException e){
            result.setErrorMsg(e.getMessage());
        }catch (DuplicateKeyException e) {
        	result.setErrorMsg("用户名已存在！");
        	log.error("create", e);
		}catch (Exception e){
        	result.setErrorMsg(e.getMessage());
            log.error("create", e);
        }
        return result.toString();
    }

	/**
	 * 更新
	 * @param user
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
    public String update(@ModelAttribute User user){
		Result<String> result = Result.errorResult();
		try{
			if(StringUtils.isBlank(user.getId())){
				result.setErrorMsg("ID不能为空！");
				return result.toString();
			}
			if(NAME_ADMIN.equalsIgnoreCase(user.getUsername())){
				result.setErrorMsg("admin用户禁止修改！");
				return result.toString();
			}
			user.setUsername(null);
			if(StringUtils.isNotBlank(user.getPassword())){
                user.setPassword(HmacSHA1Signer.signString(user.getPassword(), Constant.HMAC_SHA1_KEY));
            }
			user.setModifyTime(System.currentTimeMillis());
			UpdateResult r = userService.update(user);
			if(r.getModifiedCount()>0) {
				result.setStatus(Result.SUCCESS);
			}
		}catch (ValidatorException e){
			result.setErrorMsg(e.getMessage());
		}catch (Exception e){
			result.setErrorMsg(e.getMessage());
			log.error("create", e);
		}
		return result.toString();
	}

    /**
     * 删除
     * @param id
     * @return
     */
	@RequestMapping("/delete")
    @ResponseBody
	public String delete(@RequestParam String id, @RequestParam String userId, HttpServletRequest request){
        Result<String> result = Result.errorResult();
        UserIdentity identity = this.getSessionUser(request);
        if(userId.equalsIgnoreCase(identity.getUserId())){
            result.setErrorMsg("不能删除已登录的账户！");
            return result.toString();
        }
        User user = userService.findById(id, User.class);
        if(NAME_ADMIN.equalsIgnoreCase(user.getUsername())){
            result.setErrorMsg("admin账户禁止删除！");
            return result.toString();
        }
        DeleteResult r = userService.deleteById(id, User.class);
        if(r.getDeletedCount()>0){
            result.setStatus(Result.SUCCESS);
        }else{
            result.setErrorMsg("删除失败！");
        }
        return result.toString();
    }
}
